package com.gaohe.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.gaohe.pojo.Orders;
import com.gaohe.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private AlipayClient alipayClient;
    @Value("${ali-pay.return-url}")
    private String returnUrl;

    /*
     * 发起支付接口
     * orders 订单对象
     * return 支付页面字符串
     * */
    @Override
    public String tradeCreate(Orders orders) {
        try {
            // 创建订单
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //异步接收地址，仅支持http/https，公网可访问
            //request.setNotifyUrl("https://f0ed-221-214-86-42.ngrok.io/alipay/page/notify");
            //同步跳转地址，仅支持http/https
            request.setReturnUrl(returnUrl);

            /******必传参数******/
            JSONObject bizContent = new JSONObject();
            //商户订单号，商家自定义，保持唯一性
            bizContent.put("out_trade_no", orders.getId());
            //支付金额，最小值0.01元
            bizContent.put("total_amount", orders.getAmount());
            //订单标题，不可使用特殊符号
            bizContent.put("subject", "用户 " + orders.getUserName() + "下单~~~");
            //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            //// 扩展信息，按需传入
            //JSONObject extendParams = new JSONObject();
            //extendParams.put("sys_service_provider_id", "2088511833207846");
            //bizContent.put("extend_params", extendParams);

            request.setBizContent(bizContent.toString());
            //执行请求、调用支付宝接口
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                System.out.println("支付宝接口调用成功");
                log.info("调用成功，返回结果==》{}", response.getBody());
            } else {
                System.out.println("支付宝接口调用失败");
                log.info("调用失败，返回结果==》code:{},body:{}", response.getCode(), response.getMsg());
            }
            //返回 跳转表单
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "下单失败";
    }
}
